package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.vo.PageVO;
import com.etoak.entity.Ingredients;
import com.etoak.mapper.IngredientsMapper;
import com.etoak.service.IngredientsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-06-30
 */
@Service
public class IngredientsServiceImpl extends ServiceImpl<IngredientsMapper, Ingredients> implements IngredientsService {

    @Override
    public Ingredients getByName(String name) {
        return lambdaQuery().eq(Ingredients::getName, name).one();
    }

    @Override
    public void add(Ingredients ingredients) {
        if(ObjectUtil.isNotEmpty(this.getByName(ingredients.getName()))){
            throw new CustomException("食材名称重复");
        }

        ingredients.setCreateTime(DateUtil.now());
        this.save(ingredients);
    }

    @Override
    public List<Ingredients> getList(Ingredients ingredients) {
        return lambdaQuery().likeRight(StringUtils.isNotEmpty(ingredients.getName()),
                Ingredients::getName, ingredients.getName())
                .eq(StringUtils.isNotEmpty(ingredients.getType()), Ingredients::getType, ingredients.getType())
                .list();
    }

    @Override
    public PageVO<Ingredients> listPage(int pageNumber, int pageSize, Ingredients ingredients) {
        PageHelper.startPage(pageNumber, pageSize);
        List<Ingredients> list = this.getList(ingredients);
        PageInfo<Ingredients> pageInfo = new PageInfo<>(list);
        return new PageVO<>(list,pageInfo.getTotal());
    }

    @Override
    public void update(int id, Ingredients ingredients) {
        if(ObjectUtils.isEmpty(getById(id))){
            throw new CustomException("食材不存在");
        }

        String name = ingredients.getName();
        if(StringUtils.isNotEmpty(name)){
            Ingredients savedIngredients = getByName(name);
            if(ObjectUtils.isNotEmpty(savedIngredients) && !savedIngredients.getId().equals(id)){
                throw new CustomException("食材名称重复");
            }
        }
        ingredients.setId(id);
        ingredients.setUpdateTime(DateUtil.now());
        this.updateById(ingredients);
    }

    @Override
    public void delete(int id) {
        if(ObjectUtils.isEmpty(getById(id))){
            throw new CustomException("食材不存在");
        }
        this.removeById(id);
    }
}
